package cn.zhdst.solicitude;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.GnssStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.JsonWriter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.json.JSONObject;
import org.json.JSONStringer;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements LocationListener {
    private String protocol = "http:";
    private String domain = "172.29.8.43:9085"; //'solicitude.zhdst.cn'
    private String path = "/locationMicroService/location/record";

    private Button buttonPermission;
    private Button buttonLocation;
    private Button buttonDomain;
    private TextView textViewLocationInfo;
    private GnssStatus.Callback listener;
    private LocationManager mgr;

    private TelephonyManager tm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(MainActivity.class.getName(), "onCreate");
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //找到按钮
        buttonPermission = (Button) findViewById(R.id.buttonPermission);
        buttonLocation = (Button) findViewById(R.id.buttonLocation);
        buttonDomain = (Button) findViewById(R.id.buttonDomain);
        textViewLocationInfo = (TextView) findViewById(R.id.textViewLocationInfo);
        listener = new GnssStatus.Callback() {

        };
        buttonPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(buttonPermission.getClass().getName(), "onClick");
                if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    Log.i(buttonLocation.getClass().getName(), "=====getGeoData====01=");
                    // 权限未被授予，向用户请求权限
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 0);
                }
                if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
                    Log.i(buttonLocation.getClass().getName(), "=====getGeoData====01=");
                    // 权限未被授予，向用户请求权限
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_NETWORK_STATE}, 0);
                }
                if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
                    Log.i(buttonLocation.getClass().getName(), "=====getGeoData====01=");
                    // 权限未被授予，向用户请求权限
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.INTERNET}, 0);
                }

            }
        });
        buttonLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(buttonLocation.getClass().getName(), "onClick");
                ZhdstLocation zhdstLocation = MainActivity.this.getGeoData();
                MainActivity.this.updateGeoData(zhdstLocation);
            }
        });
        buttonDomain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(buttonDomain.getClass().getName(), "onClick");

            }
        });

    }

    private void updateGeoData(ZhdstLocation zhdstLocation) {
        String msg = "---地理信息---\n"
                + "IMEI:" + zhdstLocation.getImei() + '\n'
                + "UTC时间戳：" + zhdstLocation.getTimeStamp() + "\n"
                + "日期：" + new Date() + "\n"
                + "Boot时间戳：" + zhdstLocation.getTimeSinceBoot() + "\n"
                + "经度：" + zhdstLocation.getLatitude() + "\n"
                + "纬度：" + zhdstLocation.getLongitude() + "\n"
                + "海拔：" + zhdstLocation.getAltitude() + "\n"
                + "精度：" + zhdstLocation.getAccuracy() + "\n"
                + "速度：" + zhdstLocation.getSpeed() + "\n"
                + "航向：" + zhdstLocation.getDirection() + "\n";
        Log.i(buttonLocation.getClass().getName(), "=====updateGeoData====01=" + zhdstLocation.getFinished());

        if ( zhdstLocation.getFinished() ) {
            //系统强制要求不能在主线程中访问网络，只能在独立线程中访问
            try {
                String locationJsonStr = "locationJsonStr="
                        + new JSONStringer().object()
                        .key("imei").value(zhdstLocation.getImei())
                        .key("longitude").value(zhdstLocation.getLongitude())
                        .key("latitude").value(zhdstLocation.getLatitude())
                        .key("altitude").value(zhdstLocation.getAltitude())
                        .key("accuracy").value(zhdstLocation.getAccuracy())
                        .key("speed").value(zhdstLocation.getSpeed())
                        .key("timeStamp").value(zhdstLocation.getTimeStamp())
                        .key("direction").value(zhdstLocation.getDirection())
                        .key("timeSinceBoot").value(zhdstLocation.getTimeSinceBoot())
                        .endObject()
                        .toString();
                Log.i(buttonLocation.getClass().getName(), "=====updateGeoData====03=" + locationJsonStr);
                Record record = new Record(this.protocol + "//" + this.domain + this.path, locationJsonStr);
                Thread thread = new Thread(record);
                thread.start();
            }catch ( Exception e ) {
                //e.printStackTrace();
                Log.i(buttonLocation.getClass().getName(), "=====updateGeoData====04=" + e.toString());
            }
        }else {
            msg += "信息：";
        }
        textViewLocationInfo.setText(msg);
    }

public class Record implements Runnable {
    private String path;
    private String parameters;

    public Record(String path, String parameters) {
        this.path = path;
        this.parameters = parameters;
    }
    @Override
    public void run() {
        String result = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(this.path);
            Log.i(buttonLocation.getClass().getName(), "=====Runnable====02=" + url);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Chartset", "UTF-8");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            Log.i(Record.class.getName(), "=====Runnable====03=" + parameters);
            OutputStream os = connection.getOutputStream();
            os.write(parameters.getBytes());
            os.flush();
            os.close();
            int statusCode = connection.getResponseCode();
            if ( statusCode == 200 ) {
                InputStream in = connection.getInputStream();
                in.close();
            }
        }catch (Exception e) {
            //e.printStackTrace();
            Log.i(Record.class.getName(), "=====Runnable====04=" + e.toString());

        }finally {
            if ( connection != null ) connection.disconnect();
        }
    }
}


    private String best;
    private ZhdstLocation getGeoData() {
        ZhdstLocation zhdstLocation = new ZhdstLocation();
        if ( tm == null ) {
            //Toast.makeText((Context)this, "不是系统级应用,不能获取IMEI", Toast.LENGTH_SHORT).show();
            zhdstLocation.setError("不是系统级应用,不能获取IMEI");
            zhdstLocation.setImei("865744049416370");
        }
        mgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.i(buttonLocation.getClass().getName(), "=====getGeoData====01=");
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return zhdstLocation;
        }
        Log.i(buttonLocation.getClass().getName(), "=====getGeoData====02=");
        mgr.registerGnssStatusCallback(listener, null);
        Criteria criteria = new Criteria();
        zhdstLocation.setError(mgr.getBestProvider(criteria, true));
        Location location = mgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Log.i(buttonLocation.getClass().getName(), "=====getGeoData====03=");

        if( location != null && location.hasAccuracy() ) {
            Log.i(buttonLocation.getClass().getName(), "=====getGeoData====03.1=" + location.getAccuracy());
            zhdstLocation.setAccuracy(location.getAccuracy());
        }
        if(location != null && location.hasAltitude() ){
            Log.i(buttonLocation.getClass().getName(), "=====getGeoData====03.2=" + location.getAltitude());
            zhdstLocation.setAltitude(location.getAltitude());
        }
        if (location != null && location.hasBearing() ) {
            Log.i(buttonLocation.getClass().getName(), "=====getGeoData====03.3=" + location.hasBearing());
            zhdstLocation.setDirection(location.getBearing());
        }
        if(location != null && location.hasSpeed() ) {
            Log.i(buttonLocation.getClass().getName(), "=====getGeoData====03.4=" + location.getSpeed());
            zhdstLocation.setSpeed(location.getSpeed());
        }
        if( location != null ) {
            Log.i(buttonLocation.getClass().getName(), "=====getGeoData====03.5=" + location.getLatitude());
            zhdstLocation.setLatitude(location.getLatitude());
        }
        if( location != null ) {
            Log.i(buttonLocation.getClass().getName(), "=====getGeoData====03.6=" + location.getLongitude());
            zhdstLocation.setLongitude(location.getLongitude());
        }
        if( location != null ) {
            Log.i(buttonLocation.getClass().getName(), "=====getGeoData====03.7=" + location.getTime());
            zhdstLocation.setTimeStamp(location.getTime());
        }

        LocationManager locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(@NonNull Location location) {

            }
        };
        zhdstLocation.setFinished(true);
        return zhdstLocation;
    }

    //
    @Override
    public void onLocationChanged(@NonNull Location location) {

    }
}